<?php

namespace Biz\service\salesRebate;

use Biz\model\salesRebate\SalesAccount as mSalesAccount;
use Biz\model\salesRebate\SalesAccountLog as mSalesAccountLog;
use Biz\model\salesRebate\SalesOrder as mSalesOrder;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Doraemon\amqp\Queue;
use Doraemon\model\Phone;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\User;
use Doraemon\service\User as sUser;
use Doraemon\tools\Log;
use Medoo\Medoo;

/**
 * @deprecated
 */
class SalesAccount
{

    /**
     * 确认收货订单15天后，返佣(仅系统)
     */
    public static function createRebate($startTime)
    {
        try {
            //查询未入账（下单产生的返佣订单）的订单
            $salesOrderResult = mSalesOrder::select('*', ['status' => mSalesOrder::STATUS_NORMAL]);
            $salesOrderList = [];
            $orderNos = [];
            foreach ($salesOrderResult as $row) {
                $salesOrderList[$row['order_no']][$row['sku_id']] = $row;
                $orderNos[] = $row['order_no'];
            }
            if ($orderNos) {
                $orderGoodsResult = self::getOrderGoodsList($orderNos, $startTime);
                $orderGoodsList = $orderGoodsResult['order_goods_list'];
                $couponIds = $orderGoodsResult['coupon_ids'];
                if ($orderGoodsList && $couponIds) {
                    //符合条件的订单，计算返佣金额，更新账户金额，及更新消费记录数据
                    $result = mSalesAccount::action(function () use ($salesOrderList, $orderGoodsList) {
                        $salesAmountList = [];
                        foreach ($orderGoodsList as $orderNo => $skuList) {
                            foreach ($skuList as $row) {
                                $salesOrderInfo = isset($salesOrderList[$orderNo][$row['sku_id']]) ? $salesOrderList[$orderNo][$row['sku_id']] : [];
                                if ($salesOrderInfo) {
                                    $salesAmount = $salesOrderInfo['sale_amount'];
                                    $rate = $salesOrderInfo['rate'];
                                    $rebateAmount = bcmul($salesAmount, ($rate / 100), 2);
                                    $salesUid = $salesOrderInfo['uid'];
                                    $salesType = $salesOrderInfo['type'];
                                    if (!isset($salesAmountList[$salesUid][$salesType]['sales_amount'])) {
                                        $salesAmountList[$salesUid][$salesType]['sales_amount'] = 0;
                                    }
                                    if (!isset($salesAmountList[$salesUid][$salesType]['rebate_amount'])) {
                                        $salesAmountList[$salesUid][$salesType]['rebate_amount'] = 0;
                                    }
                                    $salesAmountList[$salesUid][$salesType]['sales_amount'] = bcadd($salesAmountList[$salesUid][$salesType]['sales_amount'], $salesAmount, 2);
                                    $salesAmountList[$salesUid][$salesType]['rebate_amount'] = bcadd($salesAmountList[$salesUid][$salesType]['rebate_amount'], $rebateAmount, 2);
                                    //update salesOrder
                                    $result = mSalesOrder::updateData(['status' => mSalesOrder::STATUS_ACCOUNTED], ['id' => $salesOrderInfo['id']]);
                                    if (!$result) {
                                        throw new \Exception('更新返佣消费记录销售金额失败');
                                    }
                                }
                            }
                        }
                        //更改salesAccount
                        foreach ($salesAmountList as $uid => $list) {
                            foreach ($list as $type => $row) {
                                $sealAmount = $row['sales_amount'];
                                $rebateAmount = $row['rebate_amount'];
                                $accountInfo = mSalesAccount::select_master("*", Medoo::raw(' where uid=:uid and type=:type for update', [
                                    ':uid' => $uid,
                                    ':type' => $type
                                ]));
                                $accountInfo = array_shift($accountInfo);
                                $logArr = [
                                    'operate_type' => mSalesAccountLog::OPERATE_TYPE_SYS_ACCOUNTED,
                                    'operate_user_type' => mSalesAccountLog::OPERATE_USER_TYPE_SYS,
                                    'operate_user_id' => 0,
                                ];
                                $result = mSalesAccount::updateAccount($accountInfo, $uid, $type, $rebateAmount, $sealAmount, $logArr);
                                if (!$result) {
                                    throw new \Exception('更新账户信息失败');
                                }
                            }
                        }
                    });
                    return $result;
                }
            }
        } catch (\Exception $e) {
            $msg = '确认收货15天后，返佣任务异常#' . '#startTime:' . $startTime . '#msg:' . json_encode([
                    'e_file' => $e->getFile(),
                    'e_line' => $e->getLine(),
                    'e_msg' => $e->getMessage()
                ], JSON_UNESCAPED_UNICODE);
            Queue::insertQueue("queue/Wechatnotice/toTag", [
                "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                "content" => $msg
            ], Queue::QUEUE_BIZ);
            Log::debug($msg);
            return false;
        }
    }

    private static function getOrderGoodsList($orderNos, $startTime)
    {
        $orderGoodsList = [];
        $couponIds = [];
        if ($orderNos) {
            //查询 订单状态为30（已完成）的订单
            $orderResult = mOrder::select([
                'order_no',
                'coupon_id',
                'coupon_vid',
                'goods_amount',
                'integral_amount',
                'coupon_amount',
                's_coupon_amount',
                'meal_amount',
                'shipping_amount',
                'pay_amount',
                'confirm_time',
                'status',
                'addtime'
            ], [
                    'confirm_time[<]' => $startTime,
                    'status' => mOrder::STATUS_SUCCESS,
                    'order_no' => $orderNos
                ]
            );
            if ($orderResult) {
                $orderNos = array_column($orderResult, 'order_no');
                $orderGoodsResult = mOrderGoods::select('*', ['order_no' => $orderNos]);
                foreach ($orderGoodsResult as $row) {
                    $orderGoodsList[$row['order_no']][$row['sku_id']] = $row;
                    $couponIds[] = $row['coupon_id'];
                }
                $orderRefundResult = mOrderRefund::select('*', ['order_no' => $orderNos]);
                foreach ($orderRefundResult as $row) {
                    $orderNo = $row['order_no'];
                    if (!in_array($row['status'], [
                        mOrderRefund::STATUS_COMPLETE,
                        mOrderRefund::STATUS_RETURN_GOODS_CANCEL,
                        mOrderRefund::STATUS_CANCEL
                    ])) {
                        //去掉正在退款中的订单商品
                        unset($orderGoodsList[$orderNo]["{$row['sku_id']}"]);
                    }
                }
            }
        }
        return [
            'order_goods_list' => $orderGoodsList,
            'coupon_ids' => array_unique($couponIds)
        ];
    }

    public static function saveAccountInfo($info)
    {
        $oldAccountInfos = self::admGetAccountByUids($info['uid']);
        if ($oldAccountInfos) {
            $oldAccountInfos = array_column($oldAccountInfos, null, 'type');
        }
        foreach (mSalesAccount::USER_TYPE_DESC as $type => $desc) {
            if (in_array($type, $info['type'])) {
                if (isset($oldAccountInfos[$type])) {
                    mSalesAccount::updateAccountInfo([
                        'belongs'    => $info['belongs'],
                        'rebate_pct' => $info['rebate_pct'][$type],
                        'status'     => mSalesAccount::STATUS_NORMAL
                    ], $info['uid'], $type);
                } else {
                    mSalesAccount::addAccountInfo([
                        'uid'        => $info['uid'],
                        'type'       => $type,
                        'belongs'    => $info['belongs'],
                        'rebate_pct' => $info['rebate_pct'][$type],
                        'status'     => mSalesAccount::STATUS_NORMAL
                    ]);
                }
            } elseif (isset($oldAccountInfos[$type])) {
                mSalesAccount::updateAccountInfo([
                    'belongs'    => $info['belongs'],
                    'rebate_pct' => $info['rebate_pct'][$type],
                    'status'     => mSalesAccount::STATUS_DELETE
                ], $info['uid'], $type);
            }
        }
    }

    public static function admGetAccountByUids($uid)
    {
        return mSalesAccount::getAccountInfosByUid($uid);
    }


    public static function admGetAccountList($filter, $limit)
    {
        if ($filter['nick'] || $filter['phone']) {
            $uid = null;
            if ($filter['nick']) {
                $uid = User::getUidByNick($filter['nick']);
            } elseif ($filter['phone']) {
                $uid = Phone::getUidByPhone(PhoneCrypto::encrypt($filter['phone'], PhoneCrypto::CLIENT_SHOP_ADMIN, PhoneCrypto::VERSIN));
            }
            if (empty($uid)) {
                return [
                    'list' => [],
                    'total' => 0
                ];
            } else {
                $filter['uid'] = $uid;
            }
        }
        $accountList = mSalesAccount::getAccountListByFilter($filter, $limit);
        $formatAccounts = ['total' => $accountList['total']];
        if ($accountList['list']) {
            $uids = array_keys($accountList['list']);
            $users = sUser::getUsers($uids);
            foreach ($accountList['list'] as $uid => $accounts) {
                $formatAccount = $users[$uid];
                $formatAccount['id'] = $uid;
                $formatAccount['valid'] = $accounts['valid'];
                $formatAccount['accounts'] = $accounts['types'];
                $formatAccounts['list'][] = $formatAccount;
            }
        }
        return $formatAccounts;
    }

}
